package paket;

import java.io.BufferedReader;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.HashMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import smarthouse.CommandManager;
import smarthouse.Smarthouse;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import commands.CommandInterface;

/**
 * Servlet implementation class SendCommand
 */
public class SendCommand extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public SendCommand() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		int deviceId = Integer.parseInt(request.getParameter("deviceId"));
		int commandId = Integer.parseInt(request.getParameter("commandId"));
		
		String str;
		String jsonText="";
		BufferedReader reader =request.getReader();
		while ((str = reader.readLine()) != null) {
			jsonText+=str;
		}
		
		HashMap<Integer, String> paramValues;
		Type type = new TypeToken<HashMap<Integer, String>>(){}.getType();
		Gson gson = new Gson();		
		paramValues = gson.fromJson(jsonText, type);
		
		CommandInterface command = CommandManager.createCommandFromStrings(deviceId, commandId, paramValues);
		Smarthouse.getInstance().sendCommand(deviceId, command);
	}

}
